package middleware

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

// RequestId automatically adds requestId
func (m *Middleware) RequestIdMiddleware(trafficKey string) gin.HandlerFunc {
	return func(c *gin.Context) {
		if c.Request.Method == http.MethodOptions {
			c.Next()
			return
		}
		requestId := c.GetHeader(trafficKey)
		if requestId == "" {
			requestId = uuid.New().String()
		}
		m.Logger.XRequestId = requestId
		// Set requestId in response header for frontend or downstream service tracking
		c.Writer.Header().Set(trafficKey, requestId)
		c.Next()
	}
}
